Set get a input field value in a form and html element content

  • 1. Form fields value

    using val()

    The jQuery val() method is mainly used to get or set the current value of the HTML form elements such as input,select and textarea.

    id or class reference are used for accessing input fields syntax:
    
                            // to get value
                            $(referenceElement).val();
    
                            //to set value
                            $(referenceElement).val('hai');
    
                          

    in html

    
                                <input type="text" id="username" name="username">
                                <input type="text" class="username" name="username">
                          
    to get value in jquery
    
                            //using id
                            var n=$('#username').val();
    
                            //using class
                            var n=$('.username').val();
                          
    to set value in jquery
    
                            //using id
                            var n=$('#username').val('manoj');
    
                            //using class
                            var n=$('.username').val('manoj');
                          
  • 2. HTML element content

    1. Using text()

    The jQuery text() method is used to get/set the text contents of the selected elements (Html content is not allowed)

    Get Contents
    
                          <p>Hi manoj</p>
                          var str = $("p").text();
                        
    Set Contents
    
                          <p>Hi manoj</p>
                          $("p").text('Hi Vineetha');
                        

    2. Using html()

    The jQuery html() method is used to get or set the HTML contents of the elements.

    Get Contents
    
                          <p><b>Hi manoj</b></p>
                          var str = $("p").html();
                        
    Set Contents
    
                          <p>Hi manoj</p>
                          $("p").html('<b>Hi Vineetha</b>');